package com.situ.mall.order.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.situ.mall.common.util.Result;
import com.situ.mall.order.pojo.vo.CartVO;
import com.situ.mall.order.service.ICartService;
import com.situ.mall.pojo.entity.order.Cart;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 购物车 前端控制器
 * </p>
 *
 * @author Sun Huijuan
 * @since 2024-10-14
 */
@RestController
@RequestMapping("/order/cart")
public class CartController {
	@Autowired
	private ICartService cartService;
	
	@PostMapping("/add")
	public Result<CartVO> add(@RequestBody Cart cart) {
		Integer num=cart.getQuantity();
		CartVO cartVO = new CartVO();
		//查找该用户有无该商品加入购物车
		Cart cart1=cartService.getOne(new QueryWrapper<Cart>().eq("user_id",cart.getUserId()).eq("product_id",cart.getProductId()));
		if(cart1!=null){
			cart.setId(cart1.getId());
			cart.setQuantity(cart1.getQuantity()+cart.getQuantity());
			cartVO=cartService.update(cart);
			cartVO.setQuantity(num);
		}else {
			cartVO =cartService.add(cart);
		}
		return Result.ok("添加成功！",cartVO);
	}
	
	@GetMapping("/selectByUserId/{userId}")
	public Result<List<CartVO>> selectByUserId(@PathVariable Long userId){
		List<CartVO> list=cartService.selectByUserId(userId);
		return Result.ok(list);
	}
	
	@GetMapping("/selectCartProduct/{id}/{pId}")
	public Result<Cart> selectCartProduct(@PathVariable Long id, @PathVariable Long pId){
		QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("user_id",id);
		queryWrapper.eq("product_id",pId);
		Cart cart=cartService.getOne(queryWrapper);
		return Result.ok(cart);
	}
	
	@DeleteMapping("/deleteById/{id}")
	public Result deleteById(@PathVariable Integer id){
		cartService.removeById(id);
		return Result.ok("删除成功！");
	}
	
	@PutMapping("/update")
	public Result update(@RequestBody Cart cart){
		cartService.updateById(cart);
		return Result.ok("修改成功！");
	}
}

